<template>
  <div>
    <FormPanel ref="formPanel" :list="formList" :cols="2" :labelWidth="110" formType="add" :isSubmitBtn="false" />
    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'center'
      }"
    >
      <el-button type="primary" icon="el-icon-printer" @click="printBalanceClick">打印结算单</el-button>
      <el-button type="primary" icon="el-icon-printer" @click="printVehicledClick">打印小修合格证</el-button>
      <el-button @click="closeDialog">取 消</el-button>
    </div>
    <div v-if="isBalanceShow">
      <BasePrint ref="print" :data="printList" template="templatePrintBalance" />
    </div>
    <div v-if="isVehicledShow">
      <BasePrint ref="printVehicled" :data="vehicledList" template="templateCertificateVehicled" />
    </div>
  </div>
</template>

<script>
import moment from 'moment';
import QRcode from 'qrcode';
import { dictionary } from '@/utils/dictMixin';
import { queryPrintData, getAdviceLabour, getAdvicePart, getRepairTypes, getLabourWorkData, getPartWorkData } from '@/api/repair/repairReception/feesSettlement';
import { searchRoleByCode } from '@/api/common/empSelect/index';
import { findAllRepair } from '@/api/repair/basicParameters';
import { getSeries, getModel } from '@/api/customerRepair/customerCare/insuranceDueRemind/index';

import dictCode from '@/utils/dictCode';
export default {
  name: 'prePrint',
  mixins: [dictionary],
  props: ['printData', 'printTitle'],
  data() {
    this.dmsFunc = { dmsFuncId: 55100010 };
    return {
      formList: this.createFormList(),
      serviceAdvisorData: [], // 服务工程师列表
      printList: {}, // 结算单数据
      vehicledList: {}, // 竣工合格证
      isBalanceShow: false,
      repairList: [], // 维修列表类型
      isVehicledShow: false
    };
  },
  created() {
    // this.formList.forEach(x => {
    //   x.initialValue = this.rowData[x.fieldName];
    // });
  },
  mounted() {
    this.getObject();
    this.getPrintData();
    this.serviceConsultant(); // 服务工程师
    this.getRepairTypesFun(); // 维修类型
    // 竣工合格证信息
    this.getWorkInfo();
    this.getLabourWork();
    this.getPartWork();
  },

  methods: {
    createFormList() {
      return [
        {
          type: 'SELECT',
          label: '收费对象',
          fieldName: 'object',
          placeholder: '请选择',
          initialValue: '',
          // disabled: true,
          change: val => {
            // this.changeBrand(val);
            // this.$refs.baseInfoFormPanel.SUBMIT_FORM();
          },
          itemList: [],
          rules: [{ required: false, message: '请选择收费对象', trigger: 'change' }]
        },
        {
          type: 'SELECT',
          label: '是否打印税额',
          fieldName: 'ISTaxAmount',
          placeholder: '请选择',
          initialValue: 10041001,
          change: val => {
            this.printList['ISTaxAmount'] = val;
          },
          itemList: this.createDictList('1004')
        },
        {
          type: 'SELECT',
          label: '是否打印维修建议',
          fieldName: 'suggesstion',
          placeholder: '请选择',
          initialValue: 10041001,
          change: val => {
            this.printList['ISSuggesstion'] = val;
          },
          itemList: this.createDictList('1004'),
          rules: [{ required: false, message: '请选择是否打印维修建议', trigger: 'change' }]
        }
      ];
    },
    // 获取收费对象
    getObject() {
      let { netReceiptsSyncTable } = this.$store.state.repairYxw;
      let arr = [];
      arr.push({ text: '全部', value: 'all' });
      netReceiptsSyncTable.forEach(x => {
        arr.push({ text: x.PAYMENT_OBJECT_NAME, value: x.PAYMENT_OBJECT_CODE });
      });
      this.formList.find(item => item.fieldName === 'object').itemList = arr;
    },
    // 获取打印数据
    async getPrintData() {
      // RO_NO BALANCE_NO
      let balanceNumber = 1;
      console.log(this.printData.BALANCE_NO, 'BALANCE_NO-----');
      if (this.printData.BALANCE_NO !== undefined) {
        console.log(4);
        balanceNumber = this.printData.BALANCE_NO;
      }
      const res = await queryPrintData(this.printData.RO_NO, balanceNumber);
      console.log(JSON.stringify(res.data), '打印数据');

      let seriesRes = await getSeries();
      // console.log(seriesRes,'seriesRes')
      let modelRes = await getModel();
      // console.log(modelRes,'modelRes')
      seriesRes.data.map(x => {
        if (x.SERIES_ID === +res.data.roInfo.SERIES) {
          this.printList['SERIES'] = x.SERIES_NAME;
        }
      });
      modelRes.data.map(x => {
        if (x.MODEL_ID === +res.data.roInfo.MODEL) {
          this.printList['MODEL'] = x.MODEL_NAME;
          this.vehicledList['MODEL'] = x.MODEL_NAME;
        }
      });
      // companyInfo
      this.printList['companyNameCn'] = res.data.companyInfo.companyNameCn;
      this.printList['companyNameEn'] = res.data.companyInfo.companyNameEn;
      this.printList['addressZh'] = res.data.companyInfo.addressZh;
      this.printList['addressEn'] = res.data.companyInfo.addressEn;
      this.printList['phone'] = res.data.companyInfo.phone;
      this.printList['zipCode'] = res.data.companyInfo.zipCode;
      this.printList['fax'] = res.data.companyInfo.fax;
      this.printList['OWNER_NAME'] = res.data.roInfo.OWNER_NAME;
      this.printList['SERVICE_ADVISOR'] = this.getEmployeeName(res.data.roInfo.SERVICE_ADVISOR);
      // roInfo
      this.printList['BALANCE_NO'] = res.data.roInfo.BALANCE_NO;
      this.printList['BALANCE_TIME'] = res.data.roInfo.BALANCE_TIME;
      this.printList['RO_NO'] = res.data.roInfo.RO_NO;
      // this.printList['RO_CREATE_DATE'] = moment(res.data.roInfo.RO_CREATE_DATE, 'YYYY-MM-DD hh:mm:ss');
      this.printList['RO_CREATE_DATE'] = res.data.roInfo.RO_CREATE_DATE;
      this.printList['CLAIM_NO'] = res.data.roInfo.CLAIM_NO;
      this.printList['REPAIR_TYPE_CODE'] = this.getRepairTypeName(res.data.roInfo.REPAIR_TYPE_CODE);
      this.printList['VIN'] = res.data.roInfo.VIN;
      this.printList['LICENSE'] = res.data.roInfo.LICENSE;
      this.printList['ENGINE_NO'] = res.data.roInfo.ENGINE_NO;
      // this.printList['SERIES'] = res.data.roInfo.SERIES;
      // this.printList['MODEL'] = res.data.roInfo.MODEL;
      this.printList['SALES_DATE'] = res.data.roInfo.SALES_DATE;
      this.printList['MILEAGE_INOUT'] = res.data.roInfo.MILEAGE_INOUT;
      this.printList['DELIVERER'] = res.data.roInfo.DELIVERER;
      this.printList['DELIVERER_MOBILE'] = res.data.roInfo.DELIVERER_MOBILE;
      this.printList['BALANCE_HANDLER'] = res.data.roInfo.BALANCE_HANDLER;
      this.printList['CUSTOMER_DESC'] = res.data.roInfo.CUSTOMER_DESC;
      this.printList['RO_TROUBLE_DESC'] = res.data.roInfo.RO_TROUBLE_DESC;
      this.printList['IS_WASH'] = this.createDictText(res.data.roInfo.IS_WASH, '1004');
      this.printList['IS_CUSTOMER_IN_ASC'] = this.createDictText(res.data.roInfo.IS_CUSTOMER_IN_ASC, '1004');
      this.printList['IS_TAKE_PART_OLD'] = this.createDictText(res.data.roInfo.IS_TAKE_PART_OLD, '1004');
      this.printList['ISTaxAmount'] = this.formList.find(item => item.fieldName === 'ISTaxAmount').initialValue;
      this.printList['ISSuggesstion'] = this.formList.find(item => item.fieldName === 'suggesstion').initialValue;
      this.printList['TaxAmount'] = res.data.roInfo.TAX_AMOUNT;
      // if(this.formList.find(item=>item.fieldName==='ISTaxAmount').initialValue===10041001){

      // }
      // this.printTableData(res.data.projectInfo, res.data.partInfo, res.data.addInfo);
      // console.log(JSON.stringify(this.printList), '------获取基础数据----');

      // 维修建议数据 BALANCE_REMARK
      this.printList['NEXT_MAINTAIN_DATE'] = res.data.roInfo.NEXT_MAINTAIN_DATE;
      this.printList['NEXT_MAINTAIN_MILEAGE'] = res.data.roInfo.NEXT_MAINTAIN_MILEAGE;
      // 二维码
      this.getqrcode(res.data.roInfo.PAYQR);

      this.getLabourAdvice();

      this.printList['BALANCE_REMARK'] = res.data.roInfo.BALANCE_REMARK;
      console.log(res.data.payObj, '实收');
      this.printTableData(res.data.labour, res.data.part, res.data.payObj, res.data.payObj);

      // 竣工合格证数据
      this.vehicledList['MILEAGE_INOUT'] = res.data.roInfo.MILEAGE_INOUT;
      this.vehicledList['OWNER_NAME'] = res.data.roInfo.OWNER_NAME;
      // this.vehicledList['MODEL'] = res.data.roInfo.MODEL;
      this.vehicledList['LICENSE'] = res.data.roInfo.LICENSE;
    },
    // 链接生成二维码
    async getqrcode(url) {
      const setUrl = await QRcode.toDataURL(url);
      this.printList['PAYQR'] = setUrl;
    },
    // 获取维修建议
    async getLabourAdvice() {
      let LABOUR_ADVICE = '';
      let advice1 = await getAdviceLabour(this.printData.VIN, this.printData.RO_NO);
      console.log(advice1, 'advice1');

      advice1.data.forEach(item => {
        LABOUR_ADVICE += item.LABOUR_NAME + ',';
      });
      let advice2 = await getAdvicePart(this.printData.VIN, this.printData.RO_NO);
      console.log(advice2, 'advice2');
      advice2.data.forEach(item => {
        LABOUR_ADVICE += item.PART_NAME + ',';
      });
      this.printList['LABOUR_ADVICE'] = LABOUR_ADVICE;
      // this.$nextTick(() => {
      //   this.printList['LABOUR_ADVICE'] = LABOUR_ADVICE;
      // });
    },

    // 代表增项 金额计算
    printTableData(maintenanceSyncTable, maintenanceMaterialsSyncTable, netReceiptsSyncTable, receivableSyncTable) {
      let that = this;
      let newObject = this.formList.find(item => item.fieldName === 'object').initialValue;
      console.log(newObject, 'newObject---');
      // 代表增项
      let itemList = [];
      // 金额计算
      let labour = 0; // 工时费
      let parts = 0; // 维修零件费
      let other = 0; // 附加费
      let total = 0; // 合计金额
      let discount = 0; // 优惠金额
      let due = 0; // 付费金额
      // 当收费对象为空或者全部时，增项显示全部信息
      if (newObject === '' || newObject === 'all') {
        maintenanceSyncTable.forEach(x => {
          if (x.CHARGE_PARTITION_CODE === 'Z') {
            itemList.push({ type: 'L', item: 'Book', description: that.getRepairTypeName(x.REPAIR_TYPE_CODE) });
            itemList.push({
              type: 'L',
              item: x.LABOUR_CODEF,
              description: x.LABOUR_NAME,
              partType: '',
              quantity: x.STD_LABOUR_HOUR,
              by: x.CHARGE_PARTITION_NAME,
              unitPrice: x.LABOUR_PRICE,
              disc: x.DISCOUNT === 1 ? '' : x.DISCOUNT * 100 + '%',
              totalPrice: x.CALC_REAL_RECEIVE_AMOUNT
            });
            itemList.push({ type: 'L', item: 'TXT', description: x.TROUBLE_CAUSE });
          } else {
            itemList.push({ type: 'L', item: 'Book', description: that.getRepairTypeName(x.REPAIR_TYPE_CODE) });
            itemList.push({
              type: 'L',
              item: x.LABOUR_CODEF,
              description: x.LABOUR_NAME,
              partType: '',
              quantity: x.STD_LABOUR_HOUR,
              by: x.CHARGE_PARTITION_NAME,
              unitPrice: '0.00',
              disc: '',
              totalPrice: '0.00'
            });
            itemList.push({ type: 'L', item: 'TXT', description: x.TROUBLE_CAUSE });
          }
          maintenanceMaterialsSyncTable.forEach(y => {
            if (x.LABOUR_CODEF === y.PART_NO) {
              if (y.CHARGE_PARTITION_CODE === 'Z') {
                itemList.push({
                  type: 'P',
                  item: y.PART_NO,
                  description: y.PART_NAME,
                  partType: y.PART_CATEGORY,
                  quantity: y.PART_QUANTITY,
                  by: y.CHARGE_PARTITION_NAME,
                  unitPrice: x.PART_SALES_PRICE,
                  disc: x.DISCOUNT === 1 ? '' : x.DISCOUNT * 100 + '%',
                  totalPrice: x.CALC_REAL_RECEIVE_AMOUNT
                });
              } else {
                itemList.push({
                  type: 'P',
                  item: y.PART_NO,
                  description: y.PART_NAME,
                  partType: y.PART_CATEGORY,
                  quantity: y.PART_QUANTITY,
                  by: y.CHARGE_PARTITION_NAME,
                  unitPrice: '0.00',
                  disc: '',
                  totalPrice: '0.00'
                });
              }
            } else {
              return;
            }
          });
        });
        netReceiptsSyncTable.forEach(x => {
          labour += Number(x.REAL_LABOUR_FEE);
          parts += Number(x.REAL_REPAIR_PART_FEE);
          other += Number(x.REAL_ADD_ITEM_FEE + x.REAL_SALES_PART_FEE);
          due += Number(x.CALC_REAL_TOTAL_AMOUNT);
        });
        receivableSyncTable.forEach(x => {
          total += Number(x.CALC_RECEIVABLE_AMOUNT);
        });
        discount = Number(total - due);
      } else if (newObject === '999999999999') {
        maintenanceSyncTable.forEach(x => {
          if (x.CHARGE_PARTITION_CODE === 'S') {
            itemList.push({ type: 'L', item: 'Book', description: that.getRepairTypeName(x.REPAIR_TYPE_CODE) });
            itemList.push({
              type: 'L',
              item: x.LABOUR_CODEF,
              description: x.LABOUR_NAME,
              partType: '',
              quantity: x.STD_LABOUR_HOUR,
              by: x.CHARGE_PARTITION_NAME,
              unitPrice: x.LABOUR_PRICE,
              disc: '',
              totalPrice: x.CALC_REAL_RECEIVE_AMOUNT
            });
            itemList.push({ type: 'L', item: 'TXT', description: x.TROUBLE_CAUSE });
          } else {
            return;
          }
          maintenanceMaterialsSyncTable.forEach(y => {
            if (x.LABOUR_CODEF === y.PART_NO) {
              if (y.CHARGE_PARTITION_CODE === 'S') {
                itemList.push({
                  type: 'P',
                  item: y.PART_NO,
                  description: y.PART_NAME,
                  partType: y.PART_CATEGORY,
                  quantity: y.PART_QUANTITY,
                  by: y.CHARGE_PARTITION_NAME,
                  unitPrice: x.PART_SALES_PRICE,
                  disc: '',
                  totalPrice: x.CALC_REAL_RECEIVE_AMOUNT
                });
              } else {
                return;
              }
            }
          });
        });
        netReceiptsSyncTable.forEach(x => {
          if (x.PAYMENT_OBJECT_CODE === '999999999999') {
            labour = Number(x.REAL_LABOUR_FEE);
            parts = Number(x.REAL_REPAIR_PART_FEE);
            other = Number(x.REAL_ADD_ITEM_FEE + x.REAL_SALES_PART_FEE);
            due = Number(x.CALC_REAL_TOTAL_AMOUNT);
          } else {
            return;
          }
        });
        receivableSyncTable.forEach(x => {
          if (x.PAYMENT_OBJECT_CODE === '999999999999') {
            total = Number(x.CALC_RECEIVABLE_AMOUNT);
          } else {
            return;
          }
        });
        discount = Number(total - due);
      } else if (newObject === '888888888888') {
        maintenanceSyncTable.forEach(x => {
          if (x.CHARGE_PARTITION_CODE !== 'Z' && x.CHARGE_PARTITION_CODE !== 'S') {
            itemList.push({ type: 'L', item: 'Book', description: that.getRepairTypeName(x.REPAIR_TYPE_CODE) });
            itemList.push({
              type: 'L',
              item: x.LABOUR_CODEF,
              description: x.LABOUR_NAME,
              partType: '',
              quantity: x.STD_LABOUR_HOUR,
              by: x.CHARGE_PARTITION_NAME,
              unitPrice: x.LABOUR_PRICE,
              disc: '',
              totalPrice: x.CALC_REAL_RECEIVE_AMOUNT
            });
            itemList.push({ type: 'L', item: 'TXT', description: x.TROUBLE_CAUSE });
          } else {
            return;
          }
          maintenanceMaterialsSyncTable.forEach(y => {
            if (x.LABOUR_CODEF === y.PART_NO) {
              if (y.CHARGE_PARTITION_CODE !== 'Z' && y.CHARGE_PARTITION_CODE !== 'S') {
                itemList.push({
                  type: 'P',
                  item: y.PART_NO,
                  description: y.PART_NAME,
                  partType: y.PART_CATEGORY,
                  quantity: y.PART_QUANTITY,
                  by: y.CHARGE_PARTITION_NAME,
                  unitPrice: x.PART_SALES_PRICE,
                  disc: '',
                  totalPrice: x.CALC_REAL_RECEIVE_AMOUNT
                });
              } else {
                return;
              }
            }
          });
        });
        netReceiptsSyncTable.forEach(x => {
          if (x.PAYMENT_OBJECT_CODE === '888888888888') {
            labour = Number(x.REAL_LABOUR_FEE);
            parts = Number(x.REAL_REPAIR_PART_FEE);
            other = Number(x.REAL_ADD_ITEM_FEE + x.REAL_SALES_PART_FEE);
            due = Number(x.CALC_REAL_TOTAL_AMOUNT);
          } else {
            return;
          }
        });
        receivableSyncTable.forEach(x => {
          if (x.PAYMENT_OBJECT_CODE === '888888888888') {
            total = Number(x.CALC_RECEIVABLE_AMOUNT);
          } else {
            return;
          }
        });
        discount = Number(total - due);
      } else {
        maintenanceSyncTable.forEach(x => {
          if (x.CHARGE_PARTITION_CODE === 'Z') {
            itemList.push({ type: 'L', item: 'Book', description: that.getRepairTypeName(x.REPAIR_TYPE_CODE) });
            itemList.push({
              type: 'L',
              item: x.LABOUR_CODEF,
              description: x.LABOUR_NAME,
              partType: '',
              quantity: x.STD_LABOUR_HOUR,
              by: x.CHARGE_PARTITION_NAME,
              unitPrice: x.LABOUR_PRICE,
              disc: x.DISCOUNT === 1 ? '' : x.DISCOUNT * 100 + '%',
              totalPrice: x.CALC_REAL_RECEIVE_AMOUNT
            });
            itemList.push({ type: 'L', item: 'TXT', description: x.TROUBLE_CAUSE });
          } else {
            return;
          }
          maintenanceMaterialsSyncTable.forEach(y => {
            if (x.LABOUR_CODEF === y.PART_NO) {
              if (y.CHARGE_PARTITION_CODE === 'Z') {
                itemList.push({
                  type: 'P',
                  item: y.PART_NO,
                  description: y.PART_NAME,
                  partType: y.PART_CATEGORY,
                  quantity: y.PART_QUANTITY,
                  by: y.CHARGE_PARTITION_NAME,
                  unitPrice: x.PART_SALES_PRICE,
                  disc: x.DISCOUNT === 1 ? '' : x.DISCOUNT * 100 + '%',
                  totalPrice: x.CALC_REAL_RECEIVE_AMOUNT
                });
              } else {
                return;
              }
            }
          });
        });
        netReceiptsSyncTable.forEach(x => {
          if (x.PAYMENT_OBJECT_CODE !== '888888888888' && x.PAYMENT_OBJECT_CODE !== '999999999999') {
            labour = Number(x.REAL_LABOUR_FEE);
            parts = Number(x.REAL_REPAIR_PART_FEE);
            other = Number(x.REAL_ADD_ITEM_FEE + x.REAL_SALES_PART_FEE);
            due = Number(x.CALC_REAL_TOTAL_AMOUNT);
          } else {
            return;
          }
        });
        receivableSyncTable.forEach(x => {
          if (x.PAYMENT_OBJECT_CODE !== '888888888888' && x.PAYMENT_OBJECT_CODE !== '999999999999') {
            total = Number(x.CALC_RECEIVABLE_AMOUNT);
          } else {
            return;
          }
        });
        discount = Number(total - due);
      }

      this.printList['itemList'] = itemList;
      this.printList['labour'] = labour;
      this.printList['parts'] = parts;
      this.printList['other'] = other;
      this.printList['due'] = due;
      this.printList['total'] = total;
      this.printList['discount'] = discount;
      console.log(JSON.stringify(this.printList), '打印数据23333');
    },
    printBalanceClick() {
      this.isBalanceShow = true;

      this.$nextTick(() => {
        this.$refs.print.EXCUTE_PRINT();
      });
    },
    printVehicledClick() {
      // this.$refs.printVehicled.EXCUTE_PRINT();

      this.isVehicledShow = true;
      this.$nextTick(() => {
        this.$refs.printVehicled.EXCUTE_PRINT();
      });
    },
    closeDialog() {
      this.$emit('close', false);
    },
    // 根据userId查employeeName
    getEmployeeName(userId) {
      const item = this.serviceAdvisorData.find(x => {
        return x.value == userId;
      });
      console.log(item, 'f服务工程师');
      return item ? item.text : '';
    },
    // 服务工程师接口数据
    async serviceConsultant() {
      let testDrive = { role: dictCode.SERVICE_CONSULTANT };
      const res = await searchRoleByCode(testDrive);
      this.serviceAdvisorData = res.data.map(x => ({ text: x.employeeName, value: x.userId }));
      console.log(JSON.stringify(this.serviceAdvisorData), '服务工程师');
    },
    // 根据code查维修类型名称
    getRepairTypeName(code) {
      const item = this.repairList.find(x => {
        return x.value == code;
      });
      return item ? item.text : '';
    },
    // 获取维修类型
    async getRepairTypesFun() {
      const res = await getRepairTypes(this.dmsFunc);
      this.repairList = res.data.map(x => ({ value: x.REPAIR_TYPE_CODE, text: x.REPAIR_TYPE_NAME }));
    },
    // 竣工合格证
    async getLabourWork() {
      // getLabourWorkData,getPartWorkData
      const res = await getLabourWorkData(this.printData.RO_NO);
      let labourData = '';
      // vehicledList
      res.data.forEach(item => {
        labourData += item.LABOUR_NAME + '；';
      });

      this.vehicledList['labourData'] = labourData;
    },
    async getPartWork() {
      const res = await getPartWorkData(this.printData.RO_NO);
      let partData = '';
      res.data.forEach(item => {
        partData += item.PART_NAME + '；';
      });

      this.vehicledList['partData'] = partData;
    },
    async getWorkInfo() {
      let res = await findAllRepair();
      console.log(res, 'res合格证');
      this.vehicledList['unit'] = res.data['7001'];
      this.vehicledList['phone'] = res.data['7002'];
    }
  }
};
</script>

<style lang="less" scoped></style>
